package com.basiclib.network

import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

class HttpService private constructor(val builder: Builder) {
    lateinit var retrofit: Retrofit


    init {
        val okHttpClient = OkHttpClient.Builder()
            .addInterceptor(builder.headInterceptor)
            .addInterceptor(builder.httpLogger)
            .connectTimeout(builder.timeOut, builder.unit)
            .readTimeout(builder.readTimeOut, builder.unit)
            .writeTimeout(builder.writeTimeOut, builder.unit)
            .build()


        retrofit = Retrofit.Builder()
            .client(okHttpClient)
            .baseUrl(builder.url)
            .addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .build()
    }

    class Builder(
        var url: String,
        var httpLogger: HttpLoggingInterceptor,
        var headInterceptor:Interceptor,
        var timeOut: Long = 30,
        var readTimeOut: Long = 30,
        var writeTimeOut: Long = 30,
        var unit: TimeUnit = TimeUnit.SECONDS
    ) {

        fun build() :Retrofit{
            return HttpService(this).retrofit
        }
    }
}